package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.api.content.model.dto.CourseBaseDTO;
import com.xuecheng.api.content.model.dto.CourseTeacherDTO;
import com.xuecheng.common.domain.code.CommonErrorCode;
import com.xuecheng.common.enums.content.CourseAuditEnum;
import com.xuecheng.common.exception.ExceptionCast;
import com.xuecheng.common.util.StringUtil;
import com.xuecheng.content.common.constant.ContentErrorCode;
import com.xuecheng.content.convert.CourseTeacherConvert;
import com.xuecheng.content.entity.CourseTeacher;
import com.xuecheng.content.mapper.CourseTeacherMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.xuecheng.content.service.CourseTeacherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 课程-教师关系表 服务实现类
 * </p>
 *
 * @author 杨佳畅
 */
@Slf4j
@Service
public class CourseTeacherServiceImpl extends ServiceImpl<CourseTeacherMapper, CourseTeacher> implements CourseTeacherService {

    @Autowired
    private CourseBaseService courseBaseService;

    @Override
    public List<CourseTeacherDTO> queryCourseTeacherById(Long courseBaseId, Long companyId) {
        if (ObjectUtils.isEmpty(courseBaseId) || ObjectUtils.isEmpty(courseBaseId)) {
            ExceptionCast.cast(CommonErrorCode.E_100101);
        }
        courseBaseService.getCourseBaseById(courseBaseId, companyId);
        LambdaQueryWrapper<CourseTeacher> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(CourseTeacher::getCourseId, courseBaseId);
        CourseTeacherMapper baseMapper = this.baseMapper;
        List<CourseTeacher> courseTeachers = baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(courseTeachers)) {
            // 若该课程没有老师，返回一个空集合
            List<CourseTeacherDTO> emptyList = Collections.emptyList();
            return emptyList;
        }
        List<CourseTeacherDTO> dtos = CourseTeacherConvert.INSTANCE.entity2dtos(courseTeachers);
        return dtos;
    }

    @Override
    @Transactional
    public CourseTeacherDTO saveOrUpdateCourseTeacher(CourseTeacherDTO dto, Long companyId) {
        CourseTeacherDTO resultDTO = null;

        if (ObjectUtils.isEmpty(dto.getCourseTeacherId())) {
            // 新增
            resultDTO = createTeacher(dto, companyId);
        } else {
            // 修改
            resultDTO = modifyTeacher(dto, companyId);
        }
        return resultDTO;
    }

    /**
     * 新增课程教师
     *
     * @param dto
     * @param companyId
     * @return
     */
    private CourseTeacherDTO createTeacher(CourseTeacherDTO dto, Long companyId) {
        CourseBaseDTO courseBase = verifyTeacherMsg(dto, companyId);
        CourseTeacher courseTeacher = CourseTeacherConvert.INSTANCE.dto2entity(dto);
        boolean saveResult = this.save(courseTeacher);
        if (!saveResult) {
            ExceptionCast.cast(ContentErrorCode.E_1200505);
        }

        CourseTeacher po = this.getById(courseTeacher.getId());
        CourseTeacherDTO resultDTO = CourseTeacherConvert.INSTANCE.entity2dto(po);
        return resultDTO;
    }

    /**
     * 修改课程教师
     *
     * @param dto
     * @param companyId
     * @return
     */
    private CourseTeacherDTO modifyTeacher(CourseTeacherDTO dto, Long companyId) {
        // TODO: 教师名称唯一性
        CourseBaseDTO courseBase = verifyTeacherMsg(dto, companyId);
        CourseTeacher courseTeacher = this.getById(dto.getCourseTeacherId());
        if (ObjectUtils.isEmpty(courseTeacher)) {
            ExceptionCast.cast(ContentErrorCode.E_1200503);
        }
        if (!ObjectUtils.nullSafeEquals(courseBase.getCourseBaseId(), courseTeacher.getCourseId())) {
            ExceptionCast.cast(ContentErrorCode.E_1200504);
        }

        LambdaUpdateWrapper<CourseTeacher> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(CourseTeacher::getTeacherName, dto.getTeacherName());
        updateWrapper.set(CourseTeacher::getPosition, dto.getPosition());
        updateWrapper.set(CourseTeacher::getPhotograph, dto.getPhotograph());
        updateWrapper.set(StringUtil.isNotBlank(dto.getIntroduction()), CourseTeacher::getIntroduction, dto.getIntroduction());
        updateWrapper.set(CourseTeacher::getCreateDate, LocalDateTime.now());
        updateWrapper.eq(CourseTeacher::getId, dto.getCourseTeacherId());
        updateWrapper.eq(CourseTeacher::getCourseId, dto.getCourseId());
        boolean updateResult = this.update(updateWrapper);
        if (!updateResult) {
            ExceptionCast.cast(ContentErrorCode.E_1200506);
        }

        CourseTeacher po = this.getById(dto.getCourseTeacherId());
        CourseTeacherDTO resultDTO = CourseTeacherConvert.INSTANCE.entity2dto(po);
        return resultDTO;
    }

    /**
     * 验证教师信息
     */
    private CourseBaseDTO verifyTeacherMsg(CourseTeacherDTO dto, Long companyId) {
        if (ObjectUtils.isEmpty(dto.getPhotograph()) ||
                ObjectUtils.isEmpty(dto.getPosition()) ||
                ObjectUtils.isEmpty(dto.getTeacherName()) ||
                ObjectUtils.isEmpty(companyId)) {
            ExceptionCast.cast(CommonErrorCode.E_100101);
        }

        CourseBaseDTO courseBase = courseBaseService.getCourseBaseById(dto.getCourseId(), companyId);
        // 获取课程状态
        String auditStatus = courseBase.getAuditStatus();
        // 判断课程审核状态
        if (CourseAuditEnum.AUDIT_COMMIT_STATUS.getCode().equals(auditStatus) ||
                CourseAuditEnum.AUDIT_PASTED_STATUS.getCode().equals(auditStatus) ||
                CourseAuditEnum.AUDIT_PUBLISHED_STATUS.getCode().equals(auditStatus)) {
            ExceptionCast.cast(ContentErrorCode.E_120015);
        }
        return courseBase;

    }

    @Override
    @Transactional
    public void removeCourseTeacherById(Long courseBaseId, Long courseTeacherId, Long companyId) {
        if (ObjectUtils.isEmpty(courseBaseId) || ObjectUtils.isEmpty(courseBaseId)) {
            ExceptionCast.cast(CommonErrorCode.E_100101);
        }

        CourseBaseDTO courseBase = courseBaseService.getCourseBaseById(courseBaseId, companyId);
        CourseTeacher courseTeacher = this.getById(courseTeacherId);
        if (ObjectUtils.isEmpty(courseTeacher)) {
            ExceptionCast.cast(ContentErrorCode.E_1200503);
        }
        if (!(ObjectUtils.nullSafeEquals(courseBase.getCourseBaseId(), courseTeacher.getCourseId()))) {
            ExceptionCast.cast(ContentErrorCode.E_1200504);
        }
        boolean removeResult = this.removeById(courseTeacherId);
        if (!removeResult) {
            ExceptionCast.cast(ContentErrorCode.E_1200501);
        }
    }
}
